﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SHOP.Areas.Admin.Models;

namespace SHOP.Areas.Admin.Controllers
{
    public class QuestionsController : Controller
    {
        //
        // GET: /Admin/Questions/
        QuestionsModelsDataContext dbQuestions = new QuestionsModelsDataContext();
        LocationsModelsDataContext dbLocations = new LocationsModelsDataContext();
        public Constants Constants = new Constants();
        public string NameController = "questions";
        public ActionResult Index()
        {
            //Delete Multi Record
            string[] items = Request.Form.GetValues("items");

            if (items != null)
            {
                foreach (var value in items)
                {
                    var ItemAccount = dbQuestions.questions.Single(b => b.id == int.Parse(value));
                    dbQuestions.questions.DeleteOnSubmit(ItemAccount);
                    dbQuestions.SubmitChanges();
                }

                return Redirect("/admin/" + NameController + "#success");
            }

            return View();
        }

        [HandleError, HttpPost]
        public ActionResult LoadContent()
        {
            string Sort_By = "";
            string Sort_Type = "";
            string Search_Type = "username";
            string KeyWord = Request.Form["keyword"];

            string[] Columns = { "username", "fullname", "email", "phone", "status", "created" };
            string sortby = Array.Find(Columns, delegate(string s) { return s == Request.Form["sort_by"]; });

            string[] Sort = { "asc", "desc" };
            string sorttype = Array.Find(Sort, delegate(string s) { return s == Request.Form["sort_type"]; });

            if (sortby != null) { Sort_By = sortby; } else { Sort_By = "id"; };
            if (sorttype != null) { Sort_Type = sorttype; } else { Sort_Type = "desc"; };

            //Pagination
            var page = int.Parse(Request.Form["page"]);
            if (KeyWord != "")
            {
                var ListItem = (from u in dbQuestions.questions select u).Where(Search_Type + ".Contains(@0)", KeyWord).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dbQuestions.questions select u).Where(Search_Type + ".Contains(@0)", KeyWord).Count();
                ViewBag.View = ListItem;

            }
            else
            {
                var ListItem = (from u in dbQuestions.questions select u).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dbQuestions.questions select u).Count();
                ViewBag.View = ListItem;
            }

            ViewBag.Page = page;
            ViewBag.Keyword = KeyWord;
            ViewBag.Sort_By = Sort_By;
            ViewBag.Sort_Type = Sort_Type;
            ViewBag.pageSize = Constants.pageSize;

            return View();
        }

        [HandleError]
        public ActionResult Update()
        {
            if (Request.QueryString["id"] != null && System.Text.RegularExpressions.Regex.IsMatch(Request.QueryString["id"], @"\d"))
            {
                //  Get id trên url
                var id = Convert.ToInt32(Request.QueryString["id"]);
                //Xuất
                var ListItem = dbQuestions.questions.SingleOrDefault(c => c.id == id);
                //Nhớ dòng này
                ViewBag.View = ListItem;
            }
            ViewBag.Locations = (from u in dbLocations.locations select u).ToList();
            return View();
        }

        [HandleError, HttpPost]
        public ActionResult Save()
        {
            var json = "";
            var answers = "";
            var match = 0;
            string[] items = Request.Form.GetValues("items");
            var code = int.Parse(Request.Form["answer"]);
            if (items != null)
            {
                foreach (var value in items)
                {
                    match++;
                    if (match == code)
                    {
                        if (answers == "")
                        {
                            answers = value + "<@@>" + 1;
                        }
                        else
                        {
                            answers = answers + "<%%>" + value + "<@@>" + 1;
                        }
                    }
                    else {
                        if (answers == "")
                        {
                            answers = value + "<@@>" + 0;
                        }
                        else
                        {
                            answers = answers + "<%%>" + value + "<@@>" + 0;
                        }
                    }
                }
            }
            
            if (Request.Form["id"] == "")
            {
                //Insert

                var ListItem = new question();

                ListItem.contents = Request.Form["contents"];
                ListItem.locationid = Convert.ToInt32(Request.Form["locationid"]);
                ListItem.answers = answers;
                ListItem.status = (Request.Form["status"] != null) ? 1 : 0;
                ListItem.changed = DateTime.Now;
                ListItem.created = DateTime.Now;

                dbQuestions.questions.InsertOnSubmit(ListItem);
                dbQuestions.SubmitChanges();

                json = "success";
            }
            else
            {
                var id = int.Parse(Request.Form["id"]);
                int recCount = dbQuestions.questions.Count(b => b.id == id);

                if (recCount > 0)
                {
                    var ListItem = dbQuestions.questions.Single(b => b.id == id);

                    ListItem.contents = Request.Form["contents"];
                    ListItem.locationid = Convert.ToInt32(Request.Form["locationid"]);
                    ListItem.answers = answers;
                    ListItem.status = (Request.Form["status"] != null) ? 1 : 0;
                    ListItem.changed = DateTime.Now;
                    ListItem.created = DateTime.Now;

                    dbQuestions.SubmitChanges();

                    json = "success";
                }
                else
                {
                    json = "fail";
                }
            }
            return Json(new { st = json });
        }

        [HandleError, HttpPost]
        public ActionResult Status()
        {
            //Update
            var json = "";

            int id = Convert.ToInt32(Request.Form["id"]);
            int recCount = dbLocations.locations.Count(b => b.id == id);

            if (recCount > 0)
            {
                var ListItem = dbLocations.locations.Single(b => b.id == id);
                ListItem.status = int.Parse(Request.Form["status"]);
                dbLocations.SubmitChanges();
                json = "success";
            }
            else
            {
                json = "fail";
            }

            return Json(new { st = json });
        }
    }
}
